#include "test.h"
#include <nxos.h>

/*
int system_test(int argc, char *argv[]);
*/

int cmpfunc1(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

static int values1[] = { 5, 20, 29, 32, 63 };
 
static int bsearch_test(void)
{
   int *item;
   int key = 32;
 
   /* 使用 bsearch() 在数组中查找值 32 */
   item = (int*) bsearch (&key, values1, 5, sizeof (int), cmpfunc1);
   if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }
   
   return(0);
}


static int values2[] = { 88, 56, 100, 2, 25 };

int cmpfunc2 (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

static int qsort_test(void)
{
   int n;

   printf("排序之前的列表：\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values2[n]);
   }

   qsort(values2, 5, sizeof(int), cmpfunc2);

   printf("\n排序之后的列表：\n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values2[n]);
   }
 
  return(0);
}

static int rand_test(void)
{
    int i, n;

    n = 5;
    
    /* 初始化随机数发生器 */
    srand((unsigned) NX_ClockGetMillisecond());
    
    /* 输出 0 到 49 之间的 5 个随机数 */
    for( i = 0 ; i < n ; i++ ) {
        printf("%d\n", rand() % 50);
    }
    
    return(0);
}

static void functionA ()
{
    printf("这是函数A\n");
}

static void functionB ()
{
    printf("这是函数B\n");
}

static int system_test(void)
{
    printf("system:%d\n", system("env"));
    printf("system:%d\n", system("echo abc 123"));
    return(0);
}

static int atexit_test(void)
{
    /* 注册终止函数 */
    atexit(functionA );
    atexit(functionB );
    
    printf("启动主程序...\n");

    printf("退出主程序...\n");

    _Exit(0);
    return(0);
}

int stdlib_test(int argc, char *argv[])
{
    qsort_test();
    bsearch_test();
    rand_test();
    system_test();
    atexit_test();
	return 0;
}
